package cn.lanca.esaypoi.util.tool;

import cn.lanca.esaypoi.c202204.week_3.v4.CommonA;
import cn.lanca.esaypoi.util.excel.ExcelListener;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import org.springframework.util.StringUtils;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author meihongliang
 * @since 2022/4/12 11:42
 */
public class ExcelUtil {
    // 根据图片地址生成图片文件

    /**
     * 读取excel
     *
     * @param excelFilePath excel文件路径
     * @param t             那个类
     * @param <T>           传入类型
     * @return List<T>
     * @throws FileNotFoundException
     */
    public static <T> List<T> readExcel(String excelFilePath, Class<T> t) throws IOException {
        ExcelListener<T> excelListener = new ExcelListener<>();
        EasyExcel.read(Files.newInputStream(new File(excelFilePath).toPath()), t, excelListener).sheet().doRead();
        return excelListener.getObjs();
    }

    /**
     * 读取excel
     *
     * @param excelFilePath excel文件路径
     * @param t             那个类
     * @param <T>           传入类型
     * @return List<T>
     * @throws FileNotFoundException
     */
    public static <T> List<T> readExcel(String excelFilePath, Class<T> t, Integer sheetNo) throws IOException {
        ExcelListener<T> excelListener = new ExcelListener<>();
        EasyExcel.read(new FileInputStream(excelFilePath), t, excelListener).sheet(sheetNo).doRead();
        return excelListener.getObjs();
    }

    /**
     * title: <font size="1"><b> </b></font><br>
     * description:<font size="1"><b> </b></font><br>
     *
     * @param fileName  导出文件本机位置 如:/Users/meihongliang/Downloads/A_xiaowan/download/xxxx.xlsx
     * @param sheetsMap sheet列表
     * @param t         具体操作那个对象,如:CommonABCDEFG.class
     * @return <br>
     * @author <a href="mail to: meihongliang@xiaowanjiankang.com" rel="nofollow">meihongliang<br>
     * @since 2022/4/24 14:30 <br>
     */
    public static <T> void writeSheetsToOneFIle(String fileName, Map<String, List<T>> sheetsMap, Class<T> t) {
        // 方法2 如果写到不同的sheet 同一个对象
        ExcelWriter excelWriter = null;
        try {
            // 这里 指定文件
            excelWriter = EasyExcel.write(fileName, t).build();
            AtomicInteger i = new AtomicInteger(0);
            for (Map.Entry<String, List<T>> stringListEntry : sheetsMap.entrySet()) {
                // 每次都要创建writeSheet 这里注意必须指定sheetNo 而且sheetName必须不一样
                WriteSheet writeSheet = EasyExcel.writerSheet(i.get(), stringListEntry.getKey()).build();
                // 分页去数据库查询数据 这里可以去数据库查询每一页的数据
                List<T> data = stringListEntry.getValue();
                excelWriter.write(data, writeSheet);
                i.incrementAndGet();
            }
        } finally {
            // 千万别忘记finish 会帮忙关闭流
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }
        System.out.println("Excel End ");
    }

    /**
     * 写入excel
     *
     * @param list          list
     * @param t             class
     * @param excelFilePath excel文件路径
     * @param <T>           传入类型
     */
    public static <T> void writeExcel(List<T> list, Class<T> t, String excelFilePath) {
        EasyExcel.write(excelFilePath, t).sheet("0_" + list.size()).doWrite(list);
    }

    /**
     * 根据url生成图片文件
     *
     * @param urlList 图片网络地址 www.xxxxxxx.xxxxx.jpg
     * @param path    图片存在系统的那个位置 图片名称是什么 baseDir/xxxx_1.jpg
     */
    public static void downloadPicture(String urlList, String path) {
        URL url = null;
        try {
            url = new URL(urlList);
            DataInputStream dataInputStream = new DataInputStream(url.openStream());
            FileOutputStream fileOutputStream = new FileOutputStream(path);
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int length;
            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            fileOutputStream.write(output.toByteArray());
            dataInputStream.close();
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static List<CommonAll> getAllDBData() throws IOException {
        return readExcel("/Users/meihongliang/Downloads/A_xiaowan/main/20220426数据库全部数据_69965.xlsx", CommonAll.class);
    }

    public static Boolean downLoadPicWithList(List<CommonA> commonBS, String baseDir, String fileName) {
        for (int m = 0; m < commonBS.size(); m++) {
            CommonA commonB = commonBS.get(m);
            String a18 = commonB.getA18();
            if (StringUtils.hasText(a18)) {
                String[] split = a18.split(",");
                System.out.println("第" + m + "条数据,图片数量:" + split.length);
                StringBuilder stringBuffer = new StringBuilder();
                for (int i = 0; i < split.length; i++) {
                    String url = split[i];
                    String picName = commonB.getA21() + "_" + commonB.getA4() + (i + 1);
                    //ExcelUtil.downloadPicture(url, baseDir + picName + ".png");
                    stringBuffer.append(picName).append(";");
                }
                commonB.setA23(stringBuffer.toString());
            }
        }
        ExcelUtil.writeExcel(commonBS, CommonA.class, fileName);
        return true;
    }
}
